﻿using AutoMapper;
using AutoMapper.Execution;
using Comain.RBAC;
using Common;
using IRepository;
using IService;
using IService.Rempos;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Service
{
    public class MemberService : IMemberService
    {
        private readonly IMapper mapper;
        IBaseRespository<T_MemberLevel> MemberLevelDAL;
        IBaseRespository<T_Member> MemberDAL;
        IBaseRespository<T_MemberRole> memberRoledal;
        private readonly IBaseRespository<T_RolePermission> respositoryss;
        private readonly IBaseRespository<T_Permission> perdal;
        private readonly IBaseRespository<T_Role> rdal;
        private readonly IBaseRespository<T_RolePermission> roleperdal;

        public MemberService(IMapper mapper,IBaseRespository<T_MemberLevel> memberLevelDAL, IBaseRespository<T_Member> memberDAL,IBaseRespository<T_MemberRole> memberRoledal,IBaseRespository<T_RolePermission> respositoryss,IBaseRespository<T_Permission> perdal,IBaseRespository<T_Role> rdal,IBaseRespository<T_RolePermission> roleperdal)
        {
            this.mapper = mapper;
            this.MemberLevelDAL = memberLevelDAL;
            this.MemberDAL = memberDAL;
            this.memberRoledal = memberRoledal;
            this.respositoryss = respositoryss;
            this.perdal = perdal;
            this.rdal = rdal;
            this.roleperdal = roleperdal;
        }

        /// <summary>
        /// 会员等级增加
        /// </summary>
        /// <param name="t">会员等级实体</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> AddMemberLevel(T_MemberLevel t)
        {
            //1.等级名称不能重复
            var res = await MemberLevelDAL.GetList().FirstOrDefaultAsync(o => o.LevelName == t.LevelName);
            if (res != null)
            {
                return -1;
            }

            //2.增加
            return await MemberLevelDAL.AddAsync(t);
        }
        /// <summary>
		/// 会员等级列表---显示
		/// </summary>
		/// <returns>返回会员等级列表</returns>
        public async Task<List<T_MemberLevel>> GetMemberList()
        {
            return await MemberLevelDAL.GetList().ToListAsync();
        }
        /// <summary>
		/// 会员增加
		/// </summary>
		/// <param name="t">会员实体</param>
		/// <returns>受影响的行数</returns>
		public async Task<int> AddMember(T_Member info, IList<int> ints)
        {
            //1.会员增加手机员不能重复
            var res = await MemberDAL.GetList().FirstOrDefaultAsync(o => o.Tel_Phone == info.Tel_Phone);
            if (res != null)
            {
                return -1;//表示手机号重复
            }
            //2.增加操作
            int count = 0;

            //2.通过事务完成会员信息、会员角色信息录入
            //BeginTransaction():开启事务   Rollback():回滚事务  Commit():提交事务
            using (var tran = MemberDAL.MyContexts.Database.BeginTransaction())
            {
                try
                {
                    //（1）完成会员信息录入
                    info.Member_Pwd = await GetUsers(info.Member_Pwd);

                    await MemberDAL.AddAsync(info);

                    //（2）完成会员角色信息录入
                    foreach (var item in ints)
                    {
                        count += await memberRoledal.AddAsync(new T_MemberRole()
                        {
                            Member_Id = info.Member_Id,
                            Role_Id = item
                        });
                    }

                    //提交事务
                    tran.Commit();
                    return count;
                }
                catch (Exception)
                {
                    //回滚事务
                    tran.Rollback();
                    throw;
                }
            }
        }


        /// <summary>
        /// 获取会员列表
        /// </summary>
        /// <param name="userName">会员名称</param>
        /// <param name="tel">手机号</param>
        /// <param name="levelId">等级id</param>
        /// <returns>会员列表</returns>

        /// <summary>
		/// 删除会员 单个删除
		/// </summary>
		/// <param name="id">会员id</param>
		/// <returns>受影响的行数</returns>
		public async Task<int> DelMemberItem(Guid id)
        {
            //1.根据Id查找某条记录
            var res = MemberDAL.GetList().FirstOrDefault(o => o.Member_Id == id);
            res.IsDeleted = true;
            //2.确认修改
            return await MemberDAL.UpdateAsync(res);
        }
		
        /// <summary>
		/// 确定修改会员
		/// </summary>
		/// <param name="t">会员实体</param>
		/// <returns>受影响的行数</returns>
		public async Task<int> UpdateMember(T_Member t)
        {
            //1.不能修改成别人的手机号（id不一样，手机号一样，未删除的数据）
            var res = MemberDAL.GetList().FirstOrDefault(o => o.Member_Id != t.Member_Id && o.Tel_Phone == t.Tel_Phone && o.IsDeleted == false);
            if (res != null)
            {
                return -1;
            }

            //2.修改
            return await MemberDAL.UpdateAsync(t);
        }

        /// <summary>
        /// Md5数据加密
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public async Task<string> GetUsers(string pwd)
        {
            MD5 md = MD5.Create();

            byte[] bytes = md.ComputeHash(Encoding.UTF8.GetBytes(pwd));

            return BitConverter.ToString(bytes).Replace("-", "");
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public async Task<LoginCommon<T_Member>> GetUsers(string? name, string pwd)
        {
            T_Member info = await MemberDAL.GetItemById(x => x.Member_Name == name);
            if(info != null)
            {
                return new LoginCommon<T_Member>()
                {
                    Login_Code = -1,
                    Login_Message = "用户名不存在"
                };
            }

            if (info.State == false)
            {
                return new LoginCommon<T_Member>()
                {
                    Login_Code = -2,
                    Login_Message = "账号已被禁用"
                };
            }

            //3.账号密码是否匹配
            if (info.Member_Pwd != await GetUsers(pwd))
            {
                return new LoginCommon<T_Member>()
                {
                    Login_Code = -3,
                    Login_Message = "账号密码不匹配"
                };
            }

            //登录成功
            return new LoginCommon<T_Member>()
            {
                Login_Code = 1,
                Login_Message = "登陆成功",
                Login_Data = info
            };
        }






        /// <summary>
        /// 角色权限
        /// </summary>
        /// <param name="info"></param>
        /// <param name="perLists"></param>
        /// <returns></returns>
        public async Task<int> AddRolePermission(T_Role info, IList<int> perLists)
        {
            //判断角色名称是否存在
            int res = rdal.GetList(x => x.Role_Name == info.Role_Name).Count();
            if (res > 0)
            {
                //角色名称已存在，阻止继续添加
                return -1;
            }

            int result = 0;

            //通过事务完成角色信息。角色权限信息录入，BeginTransaction();开启失误 Rollback()；回滚事务 Commit();提交事务
            using (var tran = rdal.MyContexts.Database.BeginTransaction())
            {
                //添加角色信息
                await rdal.AddAsync(info);
                //获取角色编号
                int roleId = info.Role_Id;
                //添加角色权限信息
                foreach (var item in perLists)
                {
                    //初始化角色权限信息
                    result += await roleperdal.AddAsync(new T_RolePermission()
                    {
                        Role_Id = roleId,
                        Permission_Id = item
                    });
                }
                //提交事务
                tran.Commit();
                return result;
            }
        }
        /// <summary>
        /// 显示
        /// </summary>
        /// <param name="index"></param>
        /// <param name="page"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task<PageComm<List<RolePerissionDTO>>> Show(int index, int page, string? name)
        {
            IQueryable<T_Permission> roo = perdal.GetList();
            if (!string.IsNullOrEmpty(name))
            {
                roo = roo.Where(x => x.Permission_Name.Contains(name));
            }
            int pindex = roo.Count();
            int psize = (int)Math.Ceiling(pindex * 1.0 / page);

            roo = roo.Skip((index - 1) * page).Take(page);

            List<RolePerissionDTO> rolePerissionDTOs = mapper.Map<List<RolePerissionDTO>>(roo);

            foreach (var item in rolePerissionDTOs)
            {
                item.Permission_RouteName = (await perdal.GetItemById(item.RolePerssion_Id)).Permission_Name;
            }

            return new PageComm<List<RolePerissionDTO>>()
            {
                Comm_MyProprty = rolePerissionDTOs,
                Comm_TotalCount = pindex,
                Comm_PageCount = psize
            };
        }

        /// <summary>
        /// 显示权限信息
        /// </summary>
        /// <returns></returns>
        public List<TreeItem> ShowPerission(int perentId)
        {
            IQueryable<T_Permission> perlist = perdal.GetList().Where(x => x.Permission_ParentId == perentId);
            List<TreeItem> treeItems = new List<TreeItem>();

            foreach (var item in perlist)
            {
                treeItems.Add(new TreeItem()
                {
                    id = item.Permission_Id,
                    label = item.Permission_Name,
                    children = ShowPerission(item.Permission_Id)
                });
            }
            return treeItems;
        }
    }
}
